//
//  UCMapView.m
//  mapmap
//
//  Created by 朱国良 on 16/7/1.
//  Copyright © 2016年 北京国泰北斗科技有限公司. All rights reserved.
//

#define TITLESIZE  256*1.8

#import "UCMapView.h"
#import <GoogleMaps/GoogleMaps.h>
#import "UCWMSTileLayer.h"
#import "UCWMSParameter.h"
#import <CoreText/CoreText.h>
#import "UCDrawRangeResult.h"
#import "UCDrawToolsClass.h"
#import "NSString+Extension.h"
#import "UCMapView+GSExtension.h"
#import "MapViewToolsView.h"
#import <YYCache/YYCache.h>
#import "AeroMapServices.h"
#import "UCMarker.h"
#import "Public.h"
#import "UCUISettings.h"
#import <objc/runtime.h>

NSString        * const AreoMapCache                    = @"AirMapSDK";
static NSString * const kAirportURL                     = @"https://www.u-cloud.cn/geoserver/ucloud/wms";
static NSString * const kTitleLayerURL                  = @"https://www.u-cloud.cn/geoserver/ucloud/wms";
static NSString * const kGoogleChinaMap                 = @"GoogleChinaMap";
static NSString * const kGoogleChinaTerrainMap          = @"GoogleChinaTerrainMap";
static NSString * const kGoogleChinaHybridMap           = @"GoogleChinaHybridMap";
static NSString * const kUcloudAirportName              = @"ucloud:airport";
static NSString * const kUcloudAirportMH                = @"airport_type=1";
static NSString * const kUcloudAirportHL                = @"airport_type=2";
static NSString * const kUcloudAirportNH                = @"airport_type=3";
static NSString * const kUcloudAirportTH                = @"airport_type=4";
static NSString * const kUcloudAirportJY                = @"airport_type=5";
static NSString * const kUcloudAirportJM                = @"airport_type=6";
static NSString * const kUcloudAirportZSJ               = @"airport_type=7";
static NSString * const kUcloudAirportJB                = @"airport_type=8";
static NSString * const kWmsTitleLayerRestrictedName    = @"ucloud:trestrictedarea";
static NSString * const kWmsTitleLayerRestrictedFilter  = @"level='R'";
static NSString * const kWmsTitleLayerNoFlyName         = @"ucloud:trestrictedarea";
static NSString * const kWmsTitleLayerNoFlyFilter       = @"level='P'";
static NSString * const kWmsTitleLayerDangerousName     = @"ucloud:trestrictedarea";
static NSString * const kWmsTitleLayerDangerousFilter   = @"level='D'";
static NSString * const kWmsTitleLayerForbiddenName     = @"ucloud:forbiddenarea_polygon";

//最大层级
const float kAMMaxZoomLevel = 20;
//最小层级
const float kAMMinZoomLevel = 2;


@interface UCMapView()<GMSMapViewDelegate,CLLocationManagerDelegate>

@property(nonatomic,copy)                 NSString                *boundString;
@property(nonatomic,strong)               CLLocationManager       *locationManager;
@property(nonatomic,strong)               UCWMSTileLayer          *mapLayer;//地图
@property(nonatomic,strong)               GMSGroundOverlay        *overLay;
@property(nonatomic,strong)               NSArray                 *UAVNewArray;//最新的无人机数据
@property(nonatomic,strong)               GMSCircle               *circle;
@property(nonatomic,strong)               NSMutableArray          *markers;
@property(nonatomic,strong)               GMSMutablePath          *path;
@property(nonatomic,strong)               GMSPolygon              *polygon;
@property(nonatomic,strong)               GMSMarker               *marker;
@property(nonatomic,assign)               UCMapType               mapType;
@property(nonatomic,strong)               MapViewToolsView        *toolView;
@property(nonatomic,strong)               YYCache                 *cache;
@property(nonatomic,strong)               UIImageView             *logoView;
@property(nonatomic,assign)               CLLocationDegrees       latitude;
@property(nonatomic,assign)               CLLocationDegrees       longitude;
@property(nonatomic,assign)               float                   zoom;
@property(nonatomic,assign,readwrite)     BOOL                    openCache;
@property(nonatomic,strong,readwrite)     CLLocation              *myLocation;
@property(nonatomic,strong,readwrite)     UCUISettings            *settings;
@property(nonatomic,strong)               GMSMapView              *map;
@end

@implementation UCMapView

- (void)dealloc{
    [_map removeObserver:self forKeyPath:@"myLocation"];
}

- (NSMutableArray *)markers{
    if (!_markers) {
        _markers = [[NSMutableArray alloc] init];
    }
    return _markers;
}
- (GMSMutablePath *)path{
    if (!_path) {
        _path = [[GMSMutablePath alloc] init];
    }
    return _path;
}
- (GMSPolygon *)polygon{
    if (!_polygon) {
        _polygon = [[GMSPolygon alloc] init];
    }
    return _polygon;
}

- (GMSMarker *)marker{
    if (_marker == nil) {
        _marker = [[GMSMarker alloc] init];
        _marker.icon = MYBUNDLE_IMAGE_PATH(@"定位");
        _marker.map = _map;
    }
    return _marker;
}

- (UCWMSTileLayer *)mapLayer{
    if (_mapLayer == nil) {
        UCWMSParameter *parameter = [[UCWMSParameter alloc] init];
        parameter.mapType = kGoogleChinaMap;
        parameter.mapView = self;
        _mapLayer = [[UCWMSTileLayer alloc] initWithLayerParameter:parameter];
        _mapLayer.titleLayerType = WMSTitleLayerMap;
        _mapLayer.openCache = self.openCache;
        _mapLayer.fadeIn = YES;
        _mapLayer.zIndex = 0;
        _mapLayer.tileSize = TITLESIZE;
    }
    return _mapLayer;
}

- (MapViewToolsView *)toolView{
    if (!_toolView) {
        _toolView = [[MapViewToolsView alloc] initWithFrame:CGRectMake(0, 0, _map.bounds.size.width, 43)];
    }
    return _toolView;
}

+ (instancetype)creatMapViewWithLocationBounds:(NSString *)bounds
                              withOpenMapCache:(BOOL)cache{
    return [[self alloc] initMapViewWithLatitude:0
                                   withLongitude:0
                                        withZoom:0
                                withOpenMapCache:cache
                                      withBounds:bounds];
}

+ (instancetype)creatMapViewWithLatitude:(CLLocationDegrees)latitude
                           withLongitude:(CLLocationDegrees)longitude
                                withZoom:(float)zoom
                        withOpenMapCache:(BOOL)cache{
    
    return [[self alloc] initMapViewWithLatitude:latitude
                                   withLongitude:longitude
                                        withZoom:zoom
                                withOpenMapCache:cache
                                      withBounds:nil];
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self loadInit];
    }
    return self;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        [self loadInit];
    }
    return self;
}

- (void)loadInit{
    self.latitude = 39.00001100;
    self.longitude = 108.1002303;
    self.zoom = 3;
    self.openCache = YES;
    self.boundString = nil;
    [self initialize];
}

- (instancetype)initMapViewWithLatitude:(CLLocationDegrees)latitude
                          withLongitude:(CLLocationDegrees)longitude
                               withZoom:(float)zoom
                       withOpenMapCache:(BOOL)cache
                             withBounds:(NSString *)bounds{
    
    self = [super init];
    
    self.openCache = cache;
    self.boundString = bounds;
    self.latitude = latitude;
    self.longitude = longitude;
    self.zoom = zoom;
    self.backgroundColor = [UIColor whiteColor];
    
    if (self) {
        [self initialize];
    }
    return self;
}

- (void)initialize{
    
    //设置初始化的定位目标
    if (_boundString == nil) {
        GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:_latitude longitude:_longitude zoom:_zoom];
        self.map = [GMSMapView new];
        _map.camera = camera;
        
    }else{
        NSString *polygon1 = [_boundString stringByReplacingOccurrencesOfString:@"POLYGON((" withString:@""];
        NSString *polygon2 = [polygon1 stringByReplacingOccurrencesOfString:@"))" withString:@""];
        NSArray *array = [polygon2 componentsSeparatedByString:@","];
        
        double lot = [[[array[0] componentsSeparatedByString:@" "] firstObject] doubleValue];
        double lat = [[[array[0] componentsSeparatedByString:@" "] lastObject] doubleValue];
        CLLocationCoordinate2D southwestCoordinate = CLLocationCoordinate2DMake(lat, lot);
        CLLocationCoordinate2D northeastCoordinate = CLLocationCoordinate2DMake(lat, lot);
        
        GMSCoordinateBounds *bounds;
        for (NSString *polygon3 in array) {
            double latititude = [[[polygon3 componentsSeparatedByString:@" "] lastObject] doubleValue];
            double longitude = [[[polygon3 componentsSeparatedByString:@" "] firstObject] doubleValue];
            
            if (southwestCoordinate.latitude > fabs(latititude)) southwestCoordinate.latitude = latititude;
            if (southwestCoordinate.longitude > fabs(longitude)) southwestCoordinate.longitude = longitude;
            if (northeastCoordinate.latitude < fabs(latititude)) northeastCoordinate.latitude = latititude;
            if (northeastCoordinate.longitude < fabs(longitude)) northeastCoordinate.longitude = longitude;
            
            bounds = [[GMSCoordinateBounds alloc] initWithCoordinate:southwestCoordinate coordinate:northeastCoordinate];
            CLLocationDegrees latitude1 = (bounds.northEast.latitude - bounds.southWest.latitude)/2;
            CLLocationDegrees longitude1 = (bounds.southWest.longitude - bounds.northEast.longitude)/2;
            GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:latitude1 longitude:longitude1 zoom:_zoom];
            self.map = [GMSMapView new];
            _map.camera = camera;
        }
        GMSCameraUpdate *cameraUpdate = [GMSCameraUpdate fitBounds:bounds];
        [_map animateWithCameraUpdate:cameraUpdate];
    }
    //禁止地图进行旋转 和指南针显示
    _map.settings.rotateGestures = NO;
    _map.settings.compassButton = YES;
    [_map setMinZoom:kAMMinZoomLevel maxZoom:kAMMaxZoomLevel];
    
    //设置地图的样式
    _map.mapType = kGMSTypeNone;
    _map.delegate = self;
    [self addSubview:_map];
    

    Ivar ivar = class_getInstanceVariable([_map class], [@"_settings" UTF8String]);
    id settings = object_getIvar(_map, ivar);
    
    unsigned int count;
    Ivar *ivarList = class_copyIvarList([settings class], &count);
    for (int i =0; i < count; i++) {
        NSString *nameStr = [NSString stringWithUTF8String:ivar_getName(ivarList[i])];
        
        if ([nameStr isEqualToString:@"_settingsView"]) {
            Ivar settingsViewIvar = class_getInstanceVariable([settings class], [nameStr UTF8String]);
            id settingsView = object_getIvar(settings, settingsViewIvar);
            Ivar logoIvar = class_getInstanceVariable([settingsView class], [@"_logo" UTF8String]);
            UIButton *logo = object_getIvar(settingsView, logoIvar);
            logo.hidden = YES;
        }
    }
    free(ivarList);
    
    [_map addSubview:self.toolView];
    //修改地图的背景图片来源
    [self changeMapView:UCMapViewSTypeNormal];
    [self creatLogoView];
    
    //设置磁盘默认缓存量
    self.cache = [YYCache cacheWithName:AreoMapCache];
    [_cache.diskCache setCountLimit:200*1024*1024];
    
    //设置mapView的UI设置项
    self.settings = [[UCUISettings alloc] init];
    [self.settings setValue:_map.settings forKey:@"settings"];
}

- (void)layoutSubviews{
    [super layoutSubviews];
    _map.frame = self.bounds;
    _logoView.frame = CGRectMake(15, CGRectGetMaxY(_map.frame)-32, 72, 22);
}

- (void)creatLogoView{
    UIImageView *imageView = [[UIImageView alloc] init];
    self.logoView = imageView;
    _logoView.image = MYBUNDLE_IMAGE_PATH(@"logo");
    [_map addSubview:imageView];
}
- (CLLocationManager *)locationManager{
    if (_locationManager == nil) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        _locationManager.distanceFilter = 10;
    }
    return _locationManager;
}

- (CLLocationCoordinate2D)wgs84ToGcj02WithPosition:(CLLocationCoordinate2D)position{
    return [self wgs84ToGcj02WithLocation:position];
}

- (CLLocationCoordinate2D)screenCoordinatesToGeographicCoordinates:(double)screenX with:(double)screenY{
    
    return [_map.projection coordinateForPoint:CGPointMake(screenX, screenY)];
}

- (CGPoint)geographicCoordinatesTurnScreenCoordinates:(CLLocationCoordinate2D)position{
    
    return [_map.projection pointForCoordinate:position];
}

- (CLLocationCoordinate2D)coordinateForPoint:(CGPoint)point{
    return [_map.projection coordinateForPoint:point];
}

//开启定位
- (void)setMyLocationEnabled:(BOOL)myLocationEnabled{
    _myLocationEnabled = myLocationEnabled;
    if (_myLocationEnabled) {
        [self.locationManager startUpdatingLocation];//开启定位
    }else{
        self.marker.map = nil;
        self.marker = nil;
        [self.locationManager stopUpdatingLocation];
    }
}

#pragma mark - CoreLocation Delegate

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    
    CLLocation *currentLocation = [locations lastObject];
    CLLocationCoordinate2D coordinate = currentLocation.coordinate;
    
    CLLocationCoordinate2D position = [self wgs84ToGcj02WithPosition:coordinate];
    CLLocation *location = [[CLLocation alloc] initWithLatitude:position.latitude longitude:position.longitude];
    
    [_map setValue:location forKey:@"myLocation"];
    self.marker.position = position;
    [self setValue:location forKey:@"myLocation"];
}

- (void)clearTileCache{
    
    [self.mapLayer clearTileCache];
}

- (void)changeMapView:(UCMapType)mapViewType{
    //先清除图层
    self.mapType = mapViewType;
    self.mapLayer.map = nil;
    switch (mapViewType) {
        case UCMapViewSTypeNormal:
            [self changeMapTitleView:kGoogleChinaMap];
            break;
        case UCMapViewTypeTerrain:
            [self changeMapTitleView:kGoogleChinaTerrainMap];
            break;
        case UCMapViewTypeSatellite:
            [self changeMapTitleView:kGoogleChinaHybridMap];
            break;
    }
}
- (void)changeMapTitleView:(NSString *)mapType{
    self.mapLayer.parameter.mapType = mapType;
    self.mapLayer.map = _map;
}
#pragma mark - 手动删除缓存
- (void)clearMapCache{
    
    [_cache removeAllObjects];
    
//    NSLog(@"删除后的缓存大小%.2f",[_cache.diskCache totalCost]/1024/1024.f);
}

- (void)setMaxCache:(NSInteger)maxCache{
    _maxCache = maxCache;
    //设置磁盘最大缓存量
    [_cache.diskCache setCountLimit:_maxCache*1024*1024];
}
- (void)setSelectedMarker:(UCMarker *)selectedMarker{
    _selectedMarker = selectedMarker;
    [_map setSelectedMarker:[selectedMarker valueForKey:@"marker"]];
}

- (void)zoomIn{
    float zoom = _map.camera.zoom+1;
    [_map animateToZoom:zoom];
}
- (void)zoomOut{
    
    float zoom = _map.camera.zoom-1;
    
    [_map animateToZoom:zoom];
}

#pragma mark - 缩放地图
- (void)mapView:(GMSMapView *)mapView didChangeCameraPosition:(GMSCameraPosition *)position{

    if ([self.delegate respondsToSelector:@selector(mapView:didChangeCameraPosition:)]) {
        [self.delegate mapView:self didChangeCameraPosition:position.target];
    }
}

- (void)mapView:(GMSMapView *)mapView idleAtCameraPosition:(GMSCameraPosition *)position{

    if ([self.delegate respondsToSelector:@selector(mapView:idleAtCameraPosition:)]) {
        [self.delegate mapView:self idleAtCameraPosition:position.target];
    }
}

#pragma mark - 移动无人机到地图中间
- (void)toMapCenter:(CLLocationCoordinate2D)position{
    dispatch_async(dispatch_get_main_queue(), ^{
        [_map animateToLocation:position];
    });
}

#pragma mark - UCMapViewDelegate
- (void)mapView:(GMSMapView *)mapView didTapAtCoordinate:(CLLocationCoordinate2D)coordinate{
    if (self.delegate && [self.delegate respondsToSelector:@selector(mapView:didTapAtCoordinate:)]) {
        [self.delegate mapView:self didTapAtCoordinate:coordinate];
    }
}

- (void)mapView:(GMSMapView *)mapView willMove:(BOOL)gesture{
    if (self.delegate && [self.delegate respondsToSelector:@selector(mapView:willMove:)]) {
        [self.delegate mapView:self willMove:gesture];
    }
}

- (void)mapView:(GMSMapView *)mapView didLongPressAtCoordinate:(CLLocationCoordinate2D)coordinate{
    if (self.delegate && [self.delegate respondsToSelector:@selector(mapView:didLongPressAtCoordinate:)]) {
        [self.delegate mapView:self didLongPressAtCoordinate:coordinate];
    }
}

- (void)mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(GMSMarker *)marker{
    if (self.delegate && [self.delegate respondsToSelector:@selector(mapView:didTapInfoWindowOfMarker:)]) {
        UCMarker *mmarker = [UCMarker markerWithPosition:marker.position];
        [mmarker setValue:marker forKey:@"marker"];
        [self.delegate mapView:self didTapInfoWindowOfMarker:mmarker];
    }
}
- (void)mapView:(GMSMapView *)mapView didLongPressInfoWindowOfMarker:(GMSMarker *)marker{
    if (self.delegate && [self.delegate respondsToSelector:@selector(mapView:didLongPressInfoWindowOfMarker:)]) {
        UCMarker *mmarker = [UCMarker markerWithPosition:marker.position];
        [mmarker setValue:marker forKey:@"marker"];
        [self.delegate mapView:self didLongPressInfoWindowOfMarker:mmarker];
    }
}

- (UIView *)mapView:(GMSMapView *)mapView markerInfoWindow:(GMSMarker *)marker{
    if (self.delegate && [self.delegate respondsToSelector:@selector(mapView:markerInfoWindow:)]) {
        UCMarker *mmarker = [UCMarker markerWithPosition:marker.position];
        [mmarker setValue:marker forKey:@"marker"];
        return [self.delegate mapView:self markerInfoWindow:mmarker];
    }
    return nil;
}
- (UIView *)mapView:(GMSMapView *)mapView markerInfoContents:(GMSMarker *)marker{
    if (self.delegate && [self.delegate respondsToSelector:@selector(mapView:markerInfoContents:)]) {
        UCMarker *mmarker = [UCMarker markerWithPosition:marker.position];
        [mmarker setValue:marker forKey:@"marker"];
        return [self.delegate mapView:self markerInfoContents:mmarker];
    }
    return nil;
}
- (void)mapView:(GMSMapView *)mapView didCloseInfoWindowOfMarker:(GMSMarker *)marker{
    if (self.delegate && [self.delegate respondsToSelector:@selector(mapView:didCloseInfoWindowOfMarker:)]) {
        UCMarker *mmarker = [UCMarker markerWithPosition:marker.position];
        [mmarker setValue:marker forKey:@"marker"];
        [self.delegate mapView:self didCloseInfoWindowOfMarker:mmarker];
    }
}
- (void)mapView:(GMSMapView *)mapView didBeginDraggingMarker:(GMSMarker *)marker{
    if (self.delegate && [self.delegate respondsToSelector:@selector(mapView:didBeginDraggingMarker:)]) {
        UCMarker *mmarker = [UCMarker markerWithPosition:marker.position];
        [mmarker setValue:marker forKey:@"marker"];
        [self.delegate mapView:self didBeginDraggingMarker:mmarker];
    }
}
- (void)mapView:(GMSMapView *)mapView didEndDraggingMarker:(GMSMarker *)marker{
    if (self.delegate && [self.delegate respondsToSelector:@selector(mapView:didEndDraggingMarker:)]) {
        UCMarker *mmarker = [UCMarker markerWithPosition:marker.position];
        [mmarker setValue:marker forKey:@"marker"];
        [self.delegate mapView:self didEndDraggingMarker:mmarker];
    }
}
- (void)mapView:(GMSMapView *)mapView didDragMarker:(GMSMarker *)marker{
    if (self.delegate && [self.delegate respondsToSelector:@selector(mapView:didDragMarker:)]) {
        UCMarker *mmarker = [UCMarker markerWithPosition:marker.position];
        [mmarker setValue:marker forKey:@"marker"];
        [self.delegate mapView:self didDragMarker:mmarker];
    }
}

- (BOOL)mapView:(GMSMapView *)mapView didTapMarker:(GMSMarker *)marker{
    if (self.delegate && [self.delegate respondsToSelector:@selector(mapView:didTapMarker:)]) {
        UCMarker *mmarker = [UCMarker markerWithPosition:marker.position];
        [mmarker setValue:marker forKey:@"marker"];
       return [self.delegate mapView:self didTapMarker:mmarker];
    }
    return NO;
}

#pragma mark - 预览绘制结果
- (void)previewGraphicsWithDrawDrangeResult:(UCDrawRangeResult *)drawRangeResult{
    
    if ([drawRangeResult.type isEqualToString:@"polygon"]) { //多边形
        NSString *polygon1 = [drawRangeResult.coord stringByReplacingOccurrencesOfString:@"POLYGON((" withString:@""];
        NSString *polygon2 = [polygon1 stringByReplacingOccurrencesOfString:@"))" withString:@""];
        NSArray *array = [polygon2 componentsSeparatedByString:@","];
        for (NSString *string in array) {
            double lot = [[[string componentsSeparatedByString:@" "] firstObject] doubleValue];
            double lat = [[[string componentsSeparatedByString:@" "] lastObject] doubleValue];
            CLLocationCoordinate2D position = CLLocationCoordinate2DMake(lat, lot);
            GMSMarker *marker = [GMSMarker markerWithPosition:position];
            marker.appearAnimation = kGMSMarkerAnimationPop;
            marker.zIndex = 1;
            [self.markers addObject:marker];
            marker.icon = [self iconForText:[NSString stringWithFormat:@"%lu",(unsigned long)self.markers.count] withBaseImage:MYBUNDLE_IMAGE_PATH(@"landing_points")];
            marker.map = _map;
            [self.path addCoordinate:position];
        }
        self.polygon.path = self.path;
        self.polygon.fillColor = [UIColor colorWithRed:246/255.0 green:221/255.0 blue:8/255.0 alpha:0.12];
        self.polygon.strokeColor = [UIColor colorWithRed:246/255.0 green:221/255.0 blue:8/255.0 alpha:1.0];
        self.polygon.strokeWidth = 1;
        self.polygon.zIndex = 5;
        self.polygon.map = _map;
        GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc] initWithPath:self.path];
        GMSCameraUpdate *cameraUpdate = [GMSCameraUpdate fitBounds:bounds];
        [_map animateWithCameraUpdate:cameraUpdate];
        
    }else if ([drawRangeResult.type isEqualToString:@"circle"]){ //圆形
        
        NSString *center = drawRangeResult.center;
        center = [center stringByReplacingOccurrencesOfString:@"POINT(" withString:@""];
        center = [center stringByReplacingOccurrencesOfString:@")" withString:@""];
        
        NSArray *array = [center componentsSeparatedByString:@","];
        double lot = [[[array[0] componentsSeparatedByString:@" "] firstObject] doubleValue];
        double lat = [[[array[0] componentsSeparatedByString:@" "] lastObject] doubleValue];
        CLLocationCoordinate2D centerPosition = CLLocationCoordinate2DMake(lat, lot);
        CLLocationDistance radius = [drawRangeResult.radius doubleValue];
        
        GMSMarker *marker = [GMSMarker markerWithPosition:centerPosition];
        marker.icon = MYBUNDLE_IMAGE_PATH(@"landing_points");
        marker.map = _map;
        
        self.circle = [GMSCircle circleWithPosition:centerPosition radius:radius];
        self.circle.map = _map;
        self.circle.fillColor = [UIColor colorWithRed:246/255.0 green:221/255.0 blue:8/255.0 alpha:0.32];
        self.circle.strokeColor = [UIColor colorWithRed:246/255.0 green:221/255.0 blue:8/255.0 alpha:1];
        self.circle.strokeWidth = 1;
        self.circle.zIndex = 5;
        
        CLLocationCoordinate2D position1 = [self getBoundsBOOL:YES withCenter:centerPosition withRadius:radius];
        CLLocationCoordinate2D position2 = [self getBoundsBOOL:NO withCenter:centerPosition withRadius:radius];
        
        GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc] initWithCoordinate:position1 coordinate:position2];
        GMSCameraUpdate *cameraUpdate = [GMSCameraUpdate fitBounds:bounds];
        [_map animateWithCameraUpdate:cameraUpdate];
    }
}
- (CLLocationCoordinate2D)getBoundsBOOL:(BOOL)positive withCenter:(CLLocationCoordinate2D)position withRadius:(CLLocationDistance)radius{
    
    double sign = positive ? 1 : -1;
    double dx = sign * radius  / 6378000 * (180/M_PI);
    double lat = position.latitude + dx;
    double lon = position.longitude + dx / cos(position.latitude * M_PI/180);
    return CLLocationCoordinate2DMake(lat, lon);
}

@end
